package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.mapper.XcUserRoleMapper;
import com.xuecheng.ucenter.model.dto.RegisterDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import com.xuecheng.ucenter.service.XcUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class XcUserServiceImpl implements XcUserService {
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    XcUserRoleMapper xcUserRoleMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void register(RegisterDto registerDto) {

        String cellphone = registerDto.getCellphone();
        //x0Dcheckcode5464，验证码校验
        getCheckcode(cellphone, registerDto);

        if(!registerDto.getConfirmpwd().equals(registerDto.getPassword())){
            XueChengPlusException.cast("密码不一致");
        }
        String username = registerDto.getUsername();
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcUser::getUsername,username);
        XcUser xcUser = xcUserMapper.selectOne(queryWrapper);
        if(xcUser!=null){
            XueChengPlusException.cast("账号已存在");
        }
        xcUser =new XcUser();
        //可以注册
        //user表
        String pwd = registerDto.getPassword();
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String pwdEncoder = passwordEncoder.encode(pwd);
        BeanUtils.copyProperties(registerDto,xcUser);
        xcUser.setCreateTime(LocalDateTime.now());
        xcUser.setPassword(pwdEncoder);
        String userId = UUID.randomUUID().toString().replaceAll("-","");
        xcUser.setId(userId);//主键
        xcUser.setUtype("101001");//学生类型
        xcUser.setStatus("1");//用户状态
        xcUserMapper.insert(xcUser);
        //user_role表
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setUserId(userId);
        xcUserRole.setCreateTime(LocalDateTime.now());
        //学生
        xcUserRole.setRoleId("17");
        xcUserRole.setId(userId);//主键
        xcUserRoleMapper.insert(xcUserRole);
        //删除验证码
        redisTemplate.delete("checkcode" + cellphone);
    }

    @Override
    public void findpassword(RegisterDto registerDto) {
        String cellphone = registerDto.getCellphone();
        if(!registerDto.getConfirmpwd().equals(registerDto.getPassword())){
            XueChengPlusException.cast("密码不一致");
        }
        LambdaQueryWrapper<XcUser> wrapper = new LambdaQueryWrapper<>();
        XcUser xcUser=null;
        String pwd = registerDto.getPassword();
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String pwdEncoder = passwordEncoder.encode(pwd);
        if(cellphone!=null){
            //验证码
            getCheckcode(cellphone, registerDto);
            wrapper.eq(XcUser::getCellphone,cellphone);
            xcUser = xcUserMapper.selectOne(wrapper);
            if(xcUser==null){
                XueChengPlusException.cast("手机号未注册");
            }
            if(!xcUser.getStatus().equals("1")){
                XueChengPlusException.cast("用户被禁用!");
            }
            BeanUtils.copyProperties(registerDto,xcUser);
            xcUser.setUpdateTime(LocalDateTime.now());
            xcUser.setPassword(pwdEncoder);
            xcUserMapper.updateById(xcUser);
        }else {
            String email = registerDto.getEmail();
            //验证码
            getCheckcode(email, registerDto);
            wrapper.eq(XcUser::getEmail,email);
            xcUser = xcUserMapper.selectOne(wrapper);
            if(xcUser==null){
                XueChengPlusException.cast("邮箱未注册");
            }
            if(!xcUser.getStatus().equals("1")){
                XueChengPlusException.cast("用户被禁用!");
            }
            BeanUtils.copyProperties(registerDto,xcUser);
            xcUser.setUpdateTime(LocalDateTime.now());
            xcUser.setPassword(pwdEncoder);
            xcUserMapper.updateById(xcUser);
        }
        //删除验证码
        redisTemplate.delete("checkcode" + cellphone);
    }


    private String getCheckcode(String phoneOrEmail,RegisterDto registerDto){
        String code = (String) redisTemplate.opsForValue().get("checkcode" + phoneOrEmail);
        if(StringUtils.isEmpty(code)){
            XueChengPlusException.cast("验证码过期");
        }
        String checkcode = registerDto.getCheckcode();
        if(!checkcode.equals(code)){
            XueChengPlusException.cast("验证码错误");
        }
        return code;
    }
}
